package com.zq.sdklib.transform

import com.android.build.api.transform.*
import com.android.build.gradle.internal.pipeline.TransformManager
import com.android.utils.FileUtils
import org.gradle.api.Project

class TransformTest : Transform {

    var project:Project

    constructor(project: Project) : super(){
        this.project = project
    }

    override fun getName(): String {
        return this::class.java.simpleName
    }

    override fun getInputTypes(): MutableSet<QualifiedContent.ContentType> {
        return TransformManager.CONTENT_CLASS
    }

    override fun getScopes(): MutableSet<in QualifiedContent.Scope> {
        return TransformManager.SCOPE_FULL_PROJECT
    }

    override fun isIncremental(): Boolean {
        return false
    }

    override fun transform(transformInvocation: TransformInvocation) {
        super.transform(transformInvocation)
        println("---- $name start ----")
        transformInvocation.inputs.forEach { transformInput ->
            transformInput.directoryInputs.forEach { directoryInput ->
                println("directoryInput=" + directoryInput.name)
                if (directoryInput.file.isDirectory()) {
                    println("--dir=" + directoryInput.file.name)
                    FileUtils.getAllFiles(directoryInput.file).forEach { file ->
                        println("----file=" + file.name)
                    }
                } else {
                    println("--file=" + directoryInput.file.name)
                }
                processDirectoryInputs(directoryInput, transformInvocation.outputProvider)
            }
            transformInput.jarInputs.forEach { jarInput ->
                println("jarInput=" + jarInput.file)
                processJarInput(jarInput, transformInvocation.outputProvider)
            }
        }
        println("---- $name end ----")
    }


    private fun processDirectoryInputs(directoryInput: DirectoryInput, outputProvider: TransformOutputProvider) {
        val dest = outputProvider.getContentLocation(
            directoryInput.name,
            directoryInput.contentTypes,
            directoryInput.scopes,
            Format.DIRECTORY
        )
        // 建立文件夹
        FileUtils.mkdirs(dest)

        // to do some transform

        // 将修改过的字节码copy到dest，就可以实现编译期间干预字节码的目的了
        println("directoryInput => " + dest)
        FileUtils.copyDirectory(directoryInput.file, dest)
    }

    private fun processJarInput(jarInput:JarInput, outputProvider:TransformOutputProvider ) {
        val dest = outputProvider.getContentLocation(
            jarInput.file.absolutePath,
            jarInput.contentTypes,
            jarInput.scopes,
            Format.JAR
        )
        // to do some transform

        // 将修改过的字节码copy到dest，就可以实现编译期间干预字节码的目的了
        println("jarInput => " + dest)
        FileUtils.copyFile(jarInput.file, dest)
    }

}